package com.example.springsecuritydemo.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;

/**
 * AES加密工具类
 * @author chenggang
 * @date 2019/04/09
 *
 */
public class AESUtil {

	private static Logger logger = LoggerFactory.getLogger(AESUtil.class);
	
	public static byte[] encrypt(String content, String password) {
		try {
			KeyGenerator kgen = KeyGenerator.getInstance("AES");
			SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
	        secureRandom.setSeed(password.getBytes());
	        kgen.init(128, secureRandom);
			SecretKey secretKey = kgen.generateKey();
			byte[] enCodeFormat = secretKey.getEncoded();
			SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
			Cipher cipher = Cipher.getInstance("AES");
			byte[] byteContent = content.getBytes("utf-8");
			cipher.init(Cipher.ENCRYPT_MODE, key);
			byte[] result = cipher.doFinal(byteContent);
			return result;
		} catch (Exception e) {
			logger.error("AES encrypt error",e);
		}
		return null;
	}
	
	/**解密
     * @param content  待解密内容
     * @param password 解密密钥
     * @return
     */
    public static byte[] decrypt(byte[] content, String password) {
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(password.getBytes());
            kgen.init(128, secureRandom);
            SecretKey secretKey = kgen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] result = cipher.doFinal(content);
            return result;
        } catch (Exception e) {
        	logger.error("AES decryt error",e);
        }
        return null;
    }
    
    //编码函数
	public static String encode(String content, String key){
        byte[] encrypt = encrypt(content, key);
        return  parseByte2HexStr(encrypt);

    }
    //解码函数
	public static String decode(String encode, String key) {
        byte[] byteDecryptResult = parseHexStr2Byte(encode);
        byte[] decryptResult = decrypt(byteDecryptResult, key);    // 普通解密
        return new String(decryptResult);
    }
    
    // 二进制转十六进制
    public static String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    // 十六进制转二进制
    public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1) {
            return null;
        }
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2),
                    16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }
    
    public static void main(String[] args) throws Exception {
    	 String content = "123456";
         String password = "leke@dong9";
         //加密
         System.out.println("加密前1：" + content);
         byte[] encryptResult = encrypt(content, password);  // 普通加密
         String strEncryptResult = parseByte2HexStr(encryptResult);
         System.out.println("加密后1：" + strEncryptResult);
         //解密
         byte[] byteDecryptResult = parseHexStr2Byte(strEncryptResult);
         byte[] decryptResult = decrypt(byteDecryptResult, password);    // 普通解密
         System.out.println("解密后1：" + new String(decryptResult));
         
         String encodeContext= encode(content, password);
         
         System.out.println("加密后2："+encodeContext);
         String value=  decode(encodeContext, password);
         System.out.println("解密后2："+value);
         
	}

}
